package com.swak.persistence.mybatis.methods.impls;

import static java.util.stream.Collectors.toList;

import java.util.List;

import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.type.JdbcType;

import com.swak.annotation.Column;
import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.utils.StringUtils;

/**
 * 对默认的ResultMap 的支持
 * 
 * @author lifeng
 * @date 2021年1月22日 下午3:08:21
 */
public class ResultMap extends AbstractMethod {

	@Override
	protected void doInject() {
		this.addResultMap();
	}

	/**
	 * 添加结果映射
	 */
	protected void addResultMap() {
		String resultMapId = this.table.getResultMap();
		if (configuration.hasResultMap(resultMapId)) {
			return;
		}
		List<ResultMapping> resultMappings = table.getColumns().stream().map(col -> this.buildResultMapping(col))
				.collect(toList());
		org.apache.ibatis.mapping.ResultMap resultMap = new org.apache.ibatis.mapping.ResultMap.Builder(configuration,
				resultMapId, this.table.entity, resultMappings).build();
		configuration.addResultMap(resultMap);
	}

	ResultMapping buildResultMapping(ColumnDefine column) {
		ResultMapping.Builder builder = new ResultMapping.Builder(configuration, column.javaProperty, column.name,
				column.javaPropertyType);
		Column define = column.define;

		// 自定义类型
		if (define != null && StringUtils.isNotBlank(define.type())) {
			builder.jdbcType(JdbcType.valueOf(define.type()));
		}

		// 自定义类型处理器
		if (define != null && StringUtils.isNotBlank(define.handler())) {

		}

		return builder.build();
	}
}